package com.ljl.ningwei.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

@Configuration
@Slf4j
public class JsonConfiguration {
    @Bean
    public ObjectMapper JsonDefaultConfig() {
        log.info("JsonConfig init start ...");
        ObjectMapper objectMapper = new ObjectMapper();
        // 返回给前端的 JSON 数据中不包含 null 值的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 忽略 JSON 中存在但 Java 对象中不存在的字段 防止报错
        // 后端返回给前端的 JSON 数据中不包含 null 值字段。
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //设置全局的时间转化
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(smt);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));//解决时区差8小时问题
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        objectMapper.registerModule(javaTimeModule);

        log.info("JsonConfig init end");
        return objectMapper;
    }
}
